<template>
  <el-drawer
    v-loading="loading"
    direction="rtl"
    :visible.sync="openh"
    size="85%"
    :before-close="close"
    append-to-body
  >

    <div style="padding: 0 20px;">
      <!-- 入库类型选择按钮 -->
      <el-button plain style="margin-right: 10px;border-radius: 0;" type="primary" @click="showForm('托')">按托入库</el-button>
      <el-button plain style="margin-right: 10px;border-radius: 0;" type="primary" @click="showForm('箱')">按箱入库</el-button>
      <el-button plain style="margin-right: 10px;border-radius: 0;" type="primary" @click="showForm('件')">按件入库</el-button>

      <!-- 按托入库抽屉 -->
      <el-drawer
        size="50%"
        title="按托入库"
        :visible.sync="showPalletForm"
        direction="rtl"
        append-to-body
        custom-class="nested-drawer"
      >
        <el-form :model="palletForm" label-width="100px">
          <el-form-item label="选择库位">
            <el-cascader
              v-model="palletForm.location"
              placeholder="请选择"
              :options="configTree"
              clearable
              filterable
              style="width: 100%;"
              :props="Cprops"
              @change="handleLocationChange('palletForm')"
            />
          </el-form-item>
          <el-form-item label="托盘码">
            <el-input v-model="palletForm.palletCode" />
          </el-form-item>
          <el-form-item label="货物状态">
            <el-select v-model="palletForm.status" placeholder="请选择货物状态">
              <el-option label="Good" value="Good" />
              <el-option label="NG" value="NG" />
              <el-option label="Hold" value="Hold" />
            </el-select>
          </el-form-item>
          <el-form-item label="箱数">
            <el-input v-model.number="palletForm.boxQuantity" type="number" />
          </el-form-item>
          <el-form-item label="总件数">
            <el-input v-model.number="palletForm.totalPieces" type="number" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('托')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <!-- 按箱入库抽屉 -->
      <el-drawer
        size="50%"
        title="按箱入库"
        :visible.sync="showBoxForm"
        direction="rtl"
        append-to-body
        custom-class="nested-drawer"
      >
        <el-form :model="boxForm" label-width="100px">
          <el-form-item label="选择库位">
            <el-cascader
              v-model="boxForm.location"
              placeholder="请选择"
              :options="configTree"
              clearable
              filterable
              style="width: 100%;"
              :props="Cprops"
              @change="handleLocationChange('boxForm')"
            />
          </el-form-item>
          <el-form-item label="托盘码">
            <el-input v-model="boxForm.palletCode" />
          </el-form-item>
          <el-form-item label="货物状态">
            <el-select v-model="boxForm.status" placeholder="请选择货物状态">
              <el-option label="Good" value="Good" />
              <el-option label="NG" value="NG" />
              <el-option label="Hold" value="Hold" />
            </el-select>
          </el-form-item>
          <el-form-item label="每箱数量">
            <el-input v-model.number="boxForm.piecesPerBox" type="number" />
          </el-form-item>
          <el-form-item label="箱子数量">
            <el-input v-model.number="boxForm.boxQuantity" type="number" @change="generateBoxInputs" />
          </el-form-item>
          <!-- 根据箱子数量生成输入框 -->
          <el-form-item v-for="(box, index) in boxForm.boxes" :key="index" :label="'箱号 ' + (index + 1)">
            <el-input v-model="box.number" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('箱')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <!-- 按件入库抽屉 -->
      <el-drawer
        size="50%"
        title="按件入库"
        :visible.sync="showPieceForm"
        direction="rtl"
        append-to-body
        custom-class="nested-drawer"
      >
        <el-form :model="pieceForm" label-width="100px">
          <el-form-item label="选择库位">
            <el-cascader
              v-model="pieceForm.location"
              placeholder="请选择"
              :options="configTree"
              clearable
              filterable
              style="width: 100%;"
              :props="Cprops"
              @change="handleLocationChange('pieceForm')"
            />
          </el-form-item>
          <el-form-item label="托盘码">
            <el-input v-model="pieceForm.palletCode" />
          </el-form-item>
          <el-form-item label="选择箱子">
            <el-button @click="fetchBoxes(pieceForm.location)">选择箱子</el-button>
            <el-select v-model="pieceForm.selectedBox" placeholder="请选择或添加箱子">
              <el-option v-for="box in pieceForm.availableBoxes" :key="box.id" :label="box.name" :value="box.id" />
              <el-option label="添加新箱子" value="new">添加新箱子</el-option>
            </el-select>
            <el-input v-if="pieceForm.selectedBox === 'new'" v-model="pieceForm.newBox" placeholder="新箱子号" />
          </el-form-item>
          <el-form-item label="货物状态">
            <el-select v-model="pieceForm.status" placeholder="请选择货物状态">
              <el-option label="Good" value="Good" />
              <el-option label="NG" value="NG" />
              <el-option label="Hold" value="Hold" />
            </el-select>
          </el-form-item>
          <el-form-item label="件数量">
            <el-input v-model.number="pieceForm.pieceQuantity" type="number" @change="generatePieceInputs" />
          </el-form-item>
          <!-- 根据件数量生成输入框 -->
          <el-form-item v-for="(piece, index) in pieceForm.pieces" :key="index" :label="'件号 ' + (index + 1)">
            <el-input v-model="piece.number" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('件')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <!-- 入库记录列表 -->
      <el-table :data="inventoryRecords" style="width: 100%">
        <el-table-column prop="type" label="入库类型">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type == '托'" effect="dark" type="success">托</el-tag>
            <el-tag v-if="scope.row.type == '箱'" effect="dark" type="danger">箱</el-tag>
            <el-tag v-if="scope.row.type == '件'" effect="dark" type="warning">件</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="palletCode" label="托盘码" />
        <el-table-column prop="boxQuantity" label="箱数" />
        <el-table-column prop="totalPieces" label="总数" />
        <el-table-column prop="status" label="货物状态" />
        <el-table-column prop="locationName" label="库位名" :formatter="formatLocation" />
        <el-table-column prop="location" label="库位ID" />
        <el-table-column prop="box_id" label="箱号" />
        <el-table-column prop="slice_id" label="件号" />
      </el-table>
    </div>

  </el-drawer>
</template>

<script>
import { locationTree } from '@/api/stock'

export default {
  // props: ['openh', 'title', 'form', 'surplus'],
  props: ['openh', 'title', 'surplus'],
  data() {
    return {
      Cprops: { value: 'config_id', label: 'name', children: 'children' },
      showPalletForm: false,
      showBoxForm: false,
      showPieceForm: false,
      palletForm: {
        location: [],
        palletCode: '',
        status: '',
        boxQuantity: 0,
        totalPieces: 0
      },
      boxForm: {
        location: [],
        palletCode: '',
        status: '',
        piecesPerBox: 0,
        boxQuantity: 0,
        boxes: []
      },
      pieceForm: {
        location: [],
        palletCode: '',
        selectedBox: '',
        newBox: '',
        status: '',
        pieceQuantity: 0,
        pieces: []
      },
      configTree: [],
      loading: false,
      inventoryRecords: []
    }
  },
  watch: {
    inventoryRecords: {
      handler(newValue, oldValue) {
        console.log('inventoryRecords', newValue)
      },
      immediate: true
    }
  },
  created() {
    this.getConfigTree()
  },
  methods: {
    getConfigTree() {
      locationTree().then(response => {
        this.configTree = response.data
      }).catch(error => {
        console.error('Error fetching location tree:', error)
      })
    },
    handleLocationChange(formName) {
      const form = this[formName]
      if (form.location.length > 0) {
        const locationIds = form.location
        // Assuming locationIds is an array of identifiers for each level
        // Fetch full location name from API based on locationIds
        this.getLocationName(locationIds).then(locationName => {
          // Set location name in the form
          this.$set(form, 'locationName', locationName)
        }).catch(error => {
          console.error('Error fetching location name:', error)
        })
      } else {
        // Clear location name if no location selected
        this.$set(form, 'locationName', '')
      }
    },
    getLocationName(locationIds) {
      // Assuming there's an API endpoint to fetch full location name based on IDs
      // Replace with your actual API endpoint
      return new Promise((resolve, reject) => {
        // Mock API call
        setTimeout(() => {
          // Replace with actual API call to fetch location name
          // Example: resolve('西安-A1-5层') for locationIds ['20240626152543', '20240626153643', '20240626153937']
          resolve('西安-A1-5层')
        }, 1000)
      })
    },
    submitForm(type) {
      let form = null
      switch (type) {
        case '托':
          form = this.palletForm
          break
        case '箱':
          form = this.boxForm
          break
        case '件':
          form = this.pieceForm
          break
        default:
          break
      }
      if (form) {
        // 判断是否是托
        if (type == '托') {
          // Push form data to inventoryRecords
          this.inventoryRecords.push({
            type,
            palletCode: form.palletCode,
            boxQuantity: form.boxQuantity,
            totalPieces: form.totalPieces,
            status: form.status,
            locationName: form.locationName,
            location: form.location,
            config_id: form.location,
            boxes: form.boxes,
            pieces: form.pieces
          })
        } else if (type == '箱') {
          form.boxes.forEach(_box => {
            this.inventoryRecords.push({
              type,
              palletCode: form.palletCode,
              boxQuantity: 1,
              totalPieces: form.piecesPerBox,
              status: form.status,
              locationName: form.locationName,
              location: form.location,
              box_id: _box.number
              // boxes: form.boxes,
              // pieces: form.pieces
            })
          })
        } else if (type == '件') {
          // pieceForm
          console.log('form.pi', form.pieces)
          form.pieces.forEach(_slice => {
            this.inventoryRecords.push({
              type,
              palletCode: form.palletCode,
              boxQuantity: 1,
              totalPieces: 1,
              status: form.status,
              locationName: form.locationName,
              location: form.location,
              box_id: form.selectedBox,
              slice_id: _slice.number
            })
          })
        }

        // Reset form
        this.resetForm(type)
      }
    },
    resetForm(type) {
      switch (type) {
        case '托':
          this.palletForm = {
            location: [],
            palletCode: '',
            status: '',
            boxQuantity: 0,
            totalPieces: 0
          }
          this.showPalletForm = false
          break
        case '箱':
          this.boxForm = {
            location: [],
            palletCode: '',
            status: '',
            piecesPerBox: 0,
            boxQuantity: 0,
            boxes: []
          }
          this.showBoxForm = false
          break
        case '件':
          this.pieceForm = {
            location: [],
            palletCode: '',
            selectedBox: '',
            newBox: '',
            status: '',
            pieceQuantity: 0,
            pieces: []
          }
          this.showPieceForm = false
          break
        default:
          break
      }
    },
    fetchBoxes(location) {
      this.pieceForm.availableBoxes = [
        { id: 1, name: 3 }
      ]

      // fetchBoxesForLocation(location).then(response => {
      //   this.pieceForm.availableBoxes = response.data
      // }).catch(error => {
      //   console.error('Error fetching boxes for location:', error)
      // })
    },
    formatLocation(row) {
      // Format location to display the full name
      return row.locationName
    },
    showForm(type) {
      switch (type) {
        case '托':
          this.showPalletForm = true
          this.showBoxForm = false
          this.showPieceForm = false
          break
        case '箱':
          this.showPalletForm = false
          this.showBoxForm = true
          this.showPieceForm = false
          break
        case '件':
          this.showPalletForm = false
          this.showBoxForm = false
          this.showPieceForm = true
          break
        default:
          break
      }
    },
    generateBoxInputs() {
      const boxQuantity = this.boxForm.boxQuantity
      this.boxForm.boxes = []
      for (let i = 0; i < boxQuantity; i++) {
        this.boxForm.boxes.push({ number: '' })
      }
    },
    generatePieceInputs() {
      const pieceQuantity = this.pieceForm.pieceQuantity
      this.pieceForm.pieces = []
      for (let i = 0; i < pieceQuantity; i++) {
        this.pieceForm.pieces.push({ number: '' })
      }
    },
    close(done) {
      this.$emit('update:openh', false)
      done()
    }
  }
}
</script>

<style scoped lang="less">
.nested-drawer {
  top: 70px;
}
</style>
